package com.baiyang.server.service.book.impl;


import com.alibaba.fastjson.JSONObject;
import com.baiyang.server.dao.book.PurchaseDetailDao;
import com.baiyang.server.dao.book.StockDao;
import com.baiyang.server.model.PageEntity;
import com.baiyang.server.model.book.PurchaseDetail;
import com.baiyang.server.model.book.Stock;
import com.baiyang.server.service.impl.BaseServiceImpl;
import com.baiyang.server.tools.DataTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.baiyang.server.dao.book.PurchaseDao;
import com.baiyang.server.model.book.Purchase;
import com.baiyang.server.service.book.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 
 * @author XVX
 * BY: @Primary 注解帮助生命@Autowired优先注入的实列
 */
@Service	
public class PurchaseServiceImpl extends BaseServiceImpl<PurchaseDao, Purchase> implements PurchaseService{
    @Autowired
    private PurchaseDao purchaseDao = null;
    @Autowired
    private PurchaseDetailDao purchaseDetailDao = null;
    @Autowired
    private StockDao stockDao = null;

    @Transactional
    @Override
    public void insertPurchase(Purchase purchase) {
        // 插入进货信息
        String id = DataTool.createUUID();
        purchase.setId(id);
        purchase.getRecords().forEach(e->{
            e.setId(DataTool.createUUID());
            e.setPurchaseId(id);
            double total = e.getPrice()*e.getNum();
            purchase.addTotalCost(total);
            // 修改库存信息
            stockDao.updateStock(e.getBookId(),e.getNum());
        });
        purchaseDao.insert(purchase);
        purchaseDetailDao.insertBatch(purchase.getRecords());
    }

    @Override
    public PageEntity<Purchase> getPagePurchase(JSONObject object) {
        PageEntity<Purchase> result = super.getPage(object);
        result.getDatas().forEach(e->{
            PurchaseDetail detail = new PurchaseDetail();
            detail.setPurchaseId(e.getId());
            List<PurchaseDetail> details = purchaseDetailDao.selectList(detail);
            e.setRecords(details);
        });
        return result;
    }
}
